<?php

/**
 * NotifyCommand class
 *
 * @author Julot <andy.julot@gmail.com>
 * @since Friday, August 5, 2011. 11:56 AM
 */
class NotifyCommand extends CConsoleCommand {

	public function getHelp() {
		return <<<EOD
USAGE
    notify [test]
DESCRIPTION
    This command will send notification mail that failed when news first
		submitted.
EOD;
	}

	public function run($args) {
		echo "Email notification started.\n";
		if ($args && $args[0] == 'test') {
			$this->_test();
		} else {
			$this->_notify();
		}
	}

	protected function _test() {
		echo "!!! TEST MODE !!!\n";

		$subject = 'Testing Senkom Information Center Email Notification';
		$body = 'Testing Senkom Information Center Email Notification';
		$notification = new NotificationMailMessage($subject, $body);

		echo 'Sending notification email... ';
		if (Yii::app()->mail->send($notification)) {
			echo "OK ^_^v\n";
		} else {
			echo "Error >_<\n";
			echo $mail->getMessage();
		}
	}

	protected function _notify() {
		$category = "application.commands.NotifyCommand";
		Yii::log('Email notification started.', "info", $category);
		
		$models = News::model()->findAll('notified=0');
		
		$total = count($models);
		echo "Found $total news.\n";
		$count = 0;
		foreach ($models as $model) {
			$count++;
			echo "Sending notification email $count of $total... ";
			if ($model->sendNotification()) {
				echo "OK ^_^v\n";
				$msg = "Notification email sent.";
				Yii::log($msg, "info", $category);
			} else {
				echo "Error >_<\n";
				$msg = 'Notification email could not be sent.';
				Yii::log($msg, "error", $category);
			}
		}
	}

}
